package Events.gui;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.Serializable;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;

import structures.Inventory;
import structures.Tradepost;
import Events.PlanetEvent;
import Events.PathEvent;
import Events.Event;
import Events.gui.components.IntField;
import structures.Spaceship;
import Items.Item;

//TODO add in Item(Action?)Listener for the TextFields (maybe a custom TextField for numbers?
//TODO add in an array to hold buy amounts


public class TradepostGUI extends JPanel implements MouseListener, Serializable{

	/**
	 * Instance GUI Stuff
	 */
	private static final long serialVersionUID = 1L;
	//private JButton next;	
	private Tradepost tradepost;
	private Inventory inventory;
	private Inventory playerInventory;
	private PathEvent planet;
	private Spaceship spaceship;
	//private JTable ItemTable;
	//private JTable ColumnHeaders;
	//private JPanel contentPane;
	//private JTextField textField;
	private JButton btnBuy, btnNext, btnSell, btnNextSell;
	private JLabel lblMoney, lblKleptons, lblPlanetName, lblPlanetNameSell, lblMoneySell;
	private JTabbedPane pane;
	private JPanel panel, panel2;
	private IntField[] fields;
	
	private int[] itemAmounts;
	
	
	/**
	 * Create the panel.
	 */
	public TradepostGUI(Tradepost tradepost) {
		super();
		this.tradepost = tradepost;
		this.planet = tradepost.getEvent();
		this.playerInventory = tradepost.getPlayerInventory();
		
		
		itemAmounts = new int[tradepost.getInventory().size()];
		for(int i = 0; i < itemAmounts.length; i++){
			itemAmounts[i] = 0;
		}
		fields = new IntField[itemAmounts.length];
		//this.inventory = inventory;
		//setLayout(null);
		this.setPreferredSize(new Dimension(600,500));
		
		// Create a child container which is to be associated with a tab
		panel = new JPanel();
		panel2 = new JPanel();
		// Add components to the panel...

		// Specify on which edge the tabs should appear
		int location = JTabbedPane.TOP; // or BOTTOM, LEFT, RIGHT

		// Create the tabbed pane
		pane = new JTabbedPane();
		pane.setPreferredSize(new Dimension(600, 500));
		add(pane);

		// Add a tab
		String label = "Buy Goods";
		pane.addTab(label, panel);
		
		
		
		//this.setLayout(new GridLayout(1, 1));
		
		
		//this.setPreferredSize(new Dimension(600,500));
		
		this.setPreferredSize(new Dimension(650,550));
		
		//BUY TAB
		JLabel lblItemHeader = new JLabel("Item");
		lblItemHeader.setAlignmentX(Component.LEFT_ALIGNMENT);
		panel.add(lblItemHeader);
		panel.add(Box.createRigidArea(new Dimension(65, 0)));
		
		JLabel lblBuyHeader = new JLabel("Qty");
		panel.add(lblBuyHeader);
		panel.add(Box.createRigidArea(new Dimension(30,0)));
		
		JLabel lblPriceHeader= new JLabel("Price");
		panel.add(lblPriceHeader);
		panel.add(Box.createRigidArea(new Dimension(10,0)));
		
		JLabel lblKleptonHeader = new JLabel("Kleptons");
		panel.add(lblKleptonHeader);
		panel.add(Box.createRigidArea(new Dimension(10,0)));
		
		JLabel lblItemDescHeader = new JLabel("Item Description");
		panel.add(lblItemDescHeader);
		panel.add(Box.createRigidArea(new Dimension(50,0)));
		
		JLabel lblBlank = new JLabel("Qty in Stock      ");
		panel.add(lblBlank);
		panel.add(Box.createRigidArea(new Dimension(10,0)));

		
		//SELL TAB
		JLabel lblItemHeaderSell = new JLabel("Item");
		lblItemHeaderSell.setAlignmentX(Component.LEFT_ALIGNMENT);
		panel2.add(lblItemHeaderSell);
		panel2.add(Box.createRigidArea(new Dimension(65, 0)));
		
		JLabel lblBuyHeaderSell = new JLabel("Qty");
		panel2.add(lblBuyHeaderSell);
		panel2.add(Box.createRigidArea(new Dimension(30,0)));
		
		JLabel lblPriceHeaderSell= new JLabel("Price");
		panel2.add(lblPriceHeaderSell);
		panel2.add(Box.createRigidArea(new Dimension(10,0)));
		
		JLabel lblKleptonHeaderSell = new JLabel("Kleptons");
		panel2.add(lblKleptonHeaderSell);
		panel2.add(Box.createRigidArea(new Dimension(10,0)));
		
		JLabel lblItemDescHeaderSell = new JLabel("Item Description");
		panel2.add(lblItemDescHeaderSell);
		panel2.add(Box.createRigidArea(new Dimension(50,0)));
		
		JLabel lblBlankSell = new JLabel("Qty in Stock      ");
		panel2.add(lblBlankSell);
		panel2.add(Box.createRigidArea(new Dimension(10,0)));
		
		fillStore();
				
		lblPlanetName = new JLabel("Planet Name: " + planet.getName());
		panel.add(lblPlanetName);
		
		lblPlanetNameSell = new JLabel("Planet Name: " + planet.getName());
		panel2.add(lblPlanetNameSell);
		
		lblMoney = new JLabel("Player Money: " + tradepost.getPlayerMoney());
		panel.add(lblMoney);
			
		lblMoneySell = new JLabel("Player Money: " + tradepost.getPlayerMoney());
		panel2.add(lblMoneySell);
		
		
		btnBuy = new JButton("Buy");
		btnBuy.addMouseListener(this);
		panel.add(btnBuy);
		
		btnSell = new JButton("Sell");
		btnSell.addMouseListener(this);
		panel2.add(btnSell);
		
		btnNext = new JButton("Head out");
		btnNext.addMouseListener(this);
		panel.add(btnNext);
		
		btnNextSell = new JButton("Head out");
		btnNextSell.addMouseListener(this);
		panel2.add(btnNextSell);
		

		
		String label2 = "Sell Goods";
		pane.addTab(label2, panel2);
		
		
		
		
		pane.addChangeListener(new ChangeListener() {
		    // This method is called whenever the selected tab changes
		    public void stateChanged(ChangeEvent evt) {
		        JTabbedPane pane = (JTabbedPane)evt.getSource();
		        System.out.println("Tab: " + pane.getSelectedIndex());
		        if(pane.getSelectedIndex() == 0){
		        	
		        }
		        // Get current tab
		        int sel = pane.getSelectedIndex();
		    }
		});
		
		
		
		revalidate();
		repaint();
	}
	
	protected JPanel createInnerPanel(String text) {
		JPanel jplPanel = new JPanel();
		JLabel jlbDisplay = new JLabel(text);
		jlbDisplay.setHorizontalAlignment(JLabel.CENTER);
		jplPanel.setLayout(new GridLayout(1, 1));
		jplPanel.add(jlbDisplay);
		return jplPanel;
	}
	
	/**
	 * Checks to see what buttons are pressed and reacts
	 * accordingly
	 */
	@Override
	public void mouseClicked(MouseEvent e) {
	    if (e.getSource() == btnBuy) {
	        //tradepost.testprint();
	        String purchasedGoods = "";
	        boolean result = tradepost.buyItems(itemAmounts);
	        if (result) {
	            for (int i = 0; i < itemAmounts.length; i++) {
	                int quant = itemAmounts[i];
	                if (quant > 0) {
	                    purchasedGoods += itemAmounts[i] + " " +  tradepost.getInventory().get(i) + "<br> ";
                        fields[i].setMaxValue(tradepost.getInventory().get(i).getQuantity());
                        fields[i].setInt(0);
	                }
	            }
	            if (!purchasedGoods.equals("")) {
	                JOptionPane.showMessageDialog(this, "<html>Thank you, you have purchased:<br> " + 
	                        purchasedGoods + "</html>", "Thank you, come again!", JOptionPane.INFORMATION_MESSAGE);
	                updatePlayerStats();
	            }
	            //tradepost.testprint();
	        }
	        else
	            for (int i = 0; i < itemAmounts.length; i++)
	                fields[i].setInt(0);
	    }
	    else if ((e.getSource() == btnNext) || (e.getSource() == btnNextSell) ) {
	        tradepost.getEvent().nextPhase();
	    }
	}
	
	@Override
	public void mouseEntered(MouseEvent e) {}
	@Override
	public void mouseExited(MouseEvent e) {}
	@Override
	public void mousePressed(MouseEvent e) {}
	@Override
	public void mouseReleased(MouseEvent e) {}
	
	/**
	 * Fill the store with all items in the Tradepost's Inventory.
	 */
	private void fillStore() {
		inventory = tradepost.getInventory();
		playerInventory = tradepost.getPlayerInventory();
		int xCoordinate = 90;
		int yCoordinate = 125;
		int ind = 0; 
		for(int i = 0; i < inventory.size(); i++){
				
				JPanel j = new JPanel();
				JPanel j2 = new JPanel();
				
				j2.setLayout(new BoxLayout(j2, BoxLayout.X_AXIS));
				j2.setPreferredSize(new Dimension(560,45));
				j2.setLocation(xCoordinate, yCoordinate);
				
				j.setLayout(new BoxLayout(j, BoxLayout.X_AXIS));
				j.setPreferredSize(new Dimension(560,45));
				j.setLocation(xCoordinate, yCoordinate);
				
				
				Dimension itemNameSize = new Dimension(100, 15);
				Dimension txtSize = new Dimension(50, 20);
				Dimension priceSize = new Dimension(50, 15);
				Dimension kleptonSize = new Dimension(70, 15);
				Dimension descSize = new Dimension(200, 15);
				Dimension stockQty = new Dimension(50, 20);
				//Dimension btn = new Dimension(75,15);
					
				//FOR THE BUY TAB					
				JLabel lblItemName = new JLabel(inventory.get(i).toString() + ":");
				//lblItemName.setSize(166,14);
				//lblItemName.setBounds(xCoordinate, yCoordinate, 166, 14);	
				lblItemName.setAlignmentX(Component.LEFT_ALIGNMENT);
				lblItemName.setMinimumSize(itemNameSize);
				lblItemName.setMaximumSize(itemNameSize);
				j.add(lblItemName);
				//j.add(new Box.Filler(minSize, prefSize, maxSize));
				
				IntField txtBuy = new IntField(inventory.get(i).getQuantity());
				txtBuy.setInt(0);
				txtBuy.getDocument().addDocumentListener(new QuantityListener(ind, itemAmounts));
				fields[ind++] = txtBuy;
				//txtBuy.setBounds(155, yCoordinate, 50, 20);
				txtBuy.setAlignmentX(Component.LEFT_ALIGNMENT);
				txtBuy.setMinimumSize(txtSize);
				txtBuy.setMaximumSize(txtSize);
				j.add(txtBuy);
				j.add(Box.createRigidArea(new Dimension(20,0)));
				txtBuy.setColumns(4);
				
				JLabel lblPrice = new JLabel(Integer.toString(inventory.get(i).getBasePrice()));
				lblPrice.setMinimumSize(priceSize);
				lblPrice.setMaximumSize(priceSize);
				//lblPrice.setBounds(230, yCoordinate, 64, 14);
				j.add(lblPrice);	
				
						
				JLabel lblKleptons = new JLabel(Integer.toString(inventory.get(i).getKlepton()));
				lblKleptons.setMinimumSize(kleptonSize);
				lblKleptons.setMaximumSize(kleptonSize);
				//lblKleptons.setBounds(305, yCoordinate, 64, 14);
				j.add(lblKleptons);
				
				
				JLabel lblItemDesc = new JLabel(inventory.get(i).getDescription());
				lblItemDesc.setMinimumSize(descSize);
				lblItemDesc.setMaximumSize(descSize);
				//lblItemDesc.setBounds(380, yCoordinate, 166, 14);
				j.add(lblItemDesc);
				
				JLabel txtStockQty = new JLabel(Integer.toString(inventory.get(i).getQuantity()));
				txtStockQty.setAlignmentX(Component.LEFT_ALIGNMENT);
				txtStockQty.setMinimumSize(stockQty);
				txtStockQty.setMaximumSize(stockQty);
				j.add(txtStockQty);
				j.add(Box.createRigidArea(new Dimension(20,0)));
	
				
				//FOR THE SELL TAB
				JLabel lblItemNameSell = new JLabel(inventory.get(i).toString() + ":");
				//lblItemName.setSize(166,14);
				//lblItemName.setBounds(xCoordinate, yCoordinate, 166, 14);	
				lblItemNameSell.setAlignmentX(Component.LEFT_ALIGNMENT);
				lblItemNameSell.setMinimumSize(itemNameSize);
				lblItemNameSell.setMaximumSize(itemNameSize);
				j2.add(lblItemNameSell);
				//j.add(new Box.Filler(minSize, prefSize, maxSize));
				
				JLabel txtSell = new JLabel(Integer.toString(inventory.get(i).getQuantity()));				
				txtSell.setAlignmentX(Component.LEFT_ALIGNMENT);
				txtSell.setMinimumSize(txtSize);
				txtSell.setMaximumSize(txtSize);
				j2.add(txtSell);
				j2.add(Box.createRigidArea(new Dimension(20,0)));	
				
				
				JLabel lblPriceSell = new JLabel(Integer.toString(inventory.get(i).getBasePrice()));
				lblPriceSell.setMinimumSize(priceSize);
				lblPriceSell.setMaximumSize(priceSize);
				//lblPrice.setBounds(230, yCoordinate, 64, 14);
				j2.add(lblPriceSell);	
				
						
				JLabel lblKleptonsSell = new JLabel(Integer.toString(inventory.get(i).getKlepton()));
				lblKleptonsSell.setMinimumSize(kleptonSize);
				lblKleptonsSell.setMaximumSize(kleptonSize);
				//lblKleptons.setBounds(305, yCoordinate, 64, 14);
				j2.add(lblKleptonsSell);
				
				
				JLabel lblItemDescSell = new JLabel(inventory.get(i).getDescription());
				lblItemDescSell.setMinimumSize(descSize);
				lblItemDescSell.setMaximumSize(descSize);
				//lblItemDesc.setBounds(380, yCoordinate, 166, 14);
				j2.add(lblItemDescSell);
				
				JLabel txtStockQtySell = new JLabel(Integer.toString(inventory.get(i).getQuantity()));
				txtStockQtySell.setAlignmentX(Component.LEFT_ALIGNMENT);
				txtStockQtySell.setMinimumSize(stockQty);
				txtStockQtySell.setMaximumSize(stockQty);
				j2.add(txtStockQtySell);
				j2.add(Box.createRigidArea(new Dimension(20,0)));
					
				
		        
		        yCoordinate = yCoordinate + 30;
		        panel.add(j);
		        panel2.add(j2);
		
		}
			
	}
	
	/**
	 * Updates the displayed player money after a transaction occurs.
	 */
	public void updatePlayerStats(){
		lblMoney.setText("Player Money: " + tradepost.getPlayerMoney());
		lblMoneySell.setText("Player Money: " + tradepost.getPlayerMoney());
		//lblKleptons.setText("Kleptons Left: " + (tradepost.getPlayerKleptons() - tradepost.getPlayerInventory().calculateKleptons()));
	}
	
	
	/**
	 * Document listener to mark changes to the value of 
	 * generated IntFields.
	 * 
	 * @author Edd Purcell
	 *
	 */
	private class QuantityListener implements DocumentListener {

		private int index;
		private int[] itemArray;
		
		/**
		 * Constructor to set up what array and which index to update
		 * @param index		index to update
		 * @param itemArray	array to update
		 */
		public QuantityListener(int index, int[] itemArray){
			this.index = index;
			this.itemArray = itemArray;
		}
		
		/**
		 * Unused
		 */
		@Override
		public void changedUpdate(DocumentEvent e) {}

		/**
		 * Update the array when the document text is changed.
		 */
		@Override
		public void insertUpdate(DocumentEvent e) {
			try{
				itemArray[index] = Integer.valueOf(e.getDocument().getText(0, e.getOffset() + 1));
			} catch(BadLocationException ex){
				itemArray[index] = 0;
			} catch(NumberFormatException ex){
				itemArray[index] = 0;
			}
		}

		/**
		 * Update the array when the document text is changed.
		 */
		@Override
		public void removeUpdate(DocumentEvent e) {
			try{
				itemArray[index] = Integer.valueOf(e.getDocument().getText(0, e.getOffset()));
			} catch(BadLocationException ex){
				itemArray[index] = 0;
			} catch(NumberFormatException ex){
				itemArray[index] = 0;
			}
		}
		
	}
}
